package com.zyp.demo.web.admin;

import com.zyp.demo.po.Tag;
import com.zyp.demo.service.TagsService;
import javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
@RequestMapping("/admin")
public class TagsController {
    @Autowired
    private TagsService tagsService;
    @GetMapping("/tags")
    public String tags(@PageableDefault(size = 3,sort = {"id"},direction = Sort.Direction.DESC)
                       Pageable pageable, Model model){
        model.addAttribute("page",tagsService.listTag(pageable));
        return "admin/tags";
    }
    @GetMapping("/tags/input")
    public String tags_input(Model model){
        model.addAttribute("tag",new Tag());//这里是为何 ？
        return "admin/tags-input";
    }
    @PostMapping("/tags")
    public String input(@Valid Tag tag, RedirectAttributes attributes){
        Tag t = tagsService.getTagByName(tag.getName());
        if (t==null){
            tagsService.saveTag(tag);
            attributes.addFlashAttribute("message","添加成功");
        }else {

            attributes.addFlashAttribute("message","不能添加重复的分类");
        }
        return  "redirect:/admin/tags";
    }
    @GetMapping("/tags/{id}/delete")
    public String delete(@PathVariable Long id){
        tagsService.deleteTag(id);
        return "redirect:/admin/tags";

    }
    @GetMapping("/tags/{id}/input")
    public String tags_edit(@PathVariable Long id,Model model){
        Tag tag = tagsService.getTag(id);
        model.addAttribute("tag",tag);
        return "admin/tags-input";
    }
    @PostMapping("/tags/{id}")
    public String tags_update(@PathVariable Long id,@Valid Tag tag,RedirectAttributes attributes) throws NotFoundException {
        Tag t = tagsService.getTag(id);
        if (t==null){
            attributes.addFlashAttribute("message","更新失败");
        }else{
            tagsService.updateTag(id, tag);
            attributes.addFlashAttribute("message","更新成功");
        }
        return "redirect:/admin/tags";
    }
}
